package cn.schoolwow.util.module.query.instanceList.flow.filter;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;
import cn.schoolwow.util.module.query.instanceList.domain.InstanceListQueryOption;

import java.util.Comparator;
import java.util.List;

public class FilterInstanceByOrderByFieldNameFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        InstanceListQueryOption instanceQueryOption = flowContext.checkInstanceData(InstanceListQueryOption.class);
        List<Object> filterInstanceList = (List<Object>) flowContext.getData("filterInstanceList");

        if(null==instanceQueryOption.orderByAscFieldName&&null==instanceQueryOption.orderByDescFieldName){
            return;
        }
        if(null!=instanceQueryOption.orderByAscFieldName){
            filterInstanceList.sort(new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    Comparable fieldValue1 = (Comparable) QueryInstance.newQuery(o1).execute().getSingleFieldValue(instanceQueryOption.orderByAscFieldName);
                    Comparable fieldValue2 = (Comparable) QueryInstance.newQuery(o2).execute().getSingleFieldValue(instanceQueryOption.orderByAscFieldName);
                    if(null!=fieldValue1&&null!=fieldValue2){
                        return fieldValue1.compareTo(fieldValue2);
                    }
                    return null==fieldValue1?-1:1;
                }
            });
        }
        if(null!=instanceQueryOption.orderByDescFieldName){
            filterInstanceList.sort(new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    Comparable fieldValue1 = (Comparable) QueryInstance.newQuery(o1).execute().getSingleFieldValue(instanceQueryOption.orderByDescFieldName);
                    Comparable fieldValue2 = (Comparable) QueryInstance.newQuery(o2).execute().getSingleFieldValue(instanceQueryOption.orderByDescFieldName);
                    if(null!=fieldValue1&&null!=fieldValue2){
                        return fieldValue2.compareTo(fieldValue1);
                    }
                    return null==fieldValue1?1:-1;
                }
            });
        }
    }

    @Override
    public String name() {
        return "指定实例列表顺序";
    }

}
